import React from 'react';
import { connect } from 'react-redux';
import { Button, Toast } from 'antd-mobile-v2';
import { ConnectProps, ConnectState } from 'typings/connect';
import { GaeaRender as Render } from '@/plugins/form/form-render/render/render.component';
import PCComponents from '@/plugins/form/form-components/index';
import createDOMForm from '@/components/rc-form/createDOMForm';
import { WrappedFormClass } from 'rc-form';
import { detailForm } from '@/services/approval';
import styles from './index.module.less';
import { IGaeaAll } from '@/plugins/form/types';
import { parseFormData } from '@/plugins/form/form-render/utils/detail-parser';
import { BPMN_APPLY_NODE_ID } from '@/plugins/constant';
import { SUCCESS_CODE } from '@/services/constant';
import ProcessSteps, { ProcessValidator, ProcessValidateResult } from '@/components/ProcessSteps';
import memoize from 'memoize-one';
import { Prompt } from 'react-router-dom';
import { clearRouteBlocker, setRouteBlocker } from '@/components/form-group/route-blocker';
import { applyType } from '@/constants';
import { getSearchName } from '@/utils/index';

interface IApprovalModal extends ConnectProps<any, any, { innerProcDefId: string; title: string }> {
  form?: WrappedFormClass<{}>;
  loading?: boolean;
}

interface IApprovalState {
  detailLoading?: boolean;
  formData: string;
  formShowData?: IGaeaAll | null;
  formValues?: IterateAny | null;
  historyTaskList: any;
  loading: boolean;
  choosePersons: any[];
}

class ApprovalModal extends React.Component<IApprovalModal, IApprovalState> {
  processValidator: ProcessValidator;
  submitType: string;
  processRef: React.RefObject<any>;
  constructor(props: IApprovalModal) {
    super(props);
    this.state = {
      detailLoading: false,
      formData: '',
      formShowData: null,
      formValues: props.defaultFormValues || null,
      historyTaskList: [],
      loading: false,
      choosePersons: []
    };
    this.processRef = null;
  }

  componentDidMount() {
    this.getApplyData();
  }

  getApplyData = async () => {
    if (!this.getSearchName('innerProcDefId')) return;// !this.props.location?.query?.innerProcDefId
    this.setState({ detailLoading: true });
    const res = await detailForm({
      innerProcDefId: this.getSearchName('innerProcDefId')
    });

    const formModelData = res.data;
    if (res && res.status == SUCCESS_CODE) {
      this.setState({
        formData: formModelData,
        formShowData: parseFormData(formModelData, BPMN_APPLY_NODE_ID)
      });
    }
  };

  getSearchName = (name?: string) => {
    const locationStr = this.props.location?.search?.split('?')?.[1];
    const arr = locationStr?.split('&');
    const obj: any = {};
    for (let i = 0; i < arr?.length; i++) {
      const aItem = arr[i]?.split('=');
      obj[aItem[0]] = decodeURIComponent(aItem[1]);
    }
    return name ? (obj?.[name] || '') : obj;
  }

  getActions = ({ extra = {}, values, flag, choosePersons = [] }) => {
    const applyName = this.getSearchName('title');
    const action = {
      type: 'capproval/startProcess',
      payload: {
        applyType: 'STOCK_RECEIVE_APPLY',
        submitFlag: flag === 'draft' ? 0 : 1,
        forms: {
          formModelData: this.state.formData,
          formValues: JSON.stringify(values)
        },
        innerProcDefId: this.getSearchName('innerProcDefId'),
        applyName,
        choosePersons,
        ...(extra ? extra : {})
      }
    };
    const applyTypeFromUrl = this.getSearchName('applyType');
    switch (applyTypeFromUrl) {
      case applyType.STUDENT_LABOUR_APPLY:
        break;
      case applyType.ONLINE_DOCUMENT_APPLY:
        action.payload.applyType = applyType.ONLINE_DOCUMENT_APPLY;
        break;
      default: break;
    }
    // console.log('action', action);
    return action;
  }

  onOk = async (flag: 'draft' | 'submit') => {
    if (this.state.loading) return;
    let values: any = null;
    let extra: any = {};
    this.submitType = flag;
    if (this.props.form && this.props.form.submitCallback) {
      const res = await this.props.form.submitCallback();
      values = res.data.formValues;
      extra = res.data.extra;
    } else {
      values = await this.props.form?.validateFields().catch((err: any) => {
        if (err && err.errors) {
          for (const k1 in this.state.formShowData) {
            for (const key in err.errors) {
              if (k1 == key) {
                const errMsg = err.errors[key]?.errors?.[0].message;
                Toast.fail(errMsg);
                return;
              }
            }
          }

        }
      });
    }
    if (!values) return;
    console.log('%c保存-----values--------------{}', 'color:green;font-size:20px;', values);

    if (extra && extra.extText?.provideItemAddList === '[]') {
      // 学生申报明细数组为空
      return Toast.fail('请填写发放明细');
    }

    // 校验申报总额
    const { userId } = this.props.userInfo;
    /**
     * userId 当前申报人id
     * principalCode 关联项目负责人id
     * projectBalance 项目余额
     * authorizeAmountUsable 可用授权金额
     * authorizeAmount 授权金额
     * matterTotalUseAble 事项余额
     * totalAmount 申报总额
     */
    try {
      let { principalCode, projectBalance, authorizeAmountUsable, authorizeAmount } = values.projectId || {};
      authorizeAmount = authorizeAmount == -1 ? Infinity : authorizeAmount;

      const { totalAmount } = values;
      let matterTotalUseAble;
      // 关联事项非必选不判断事项余额
      if (!values.relatedMattersAddList?.value?.length) {
        matterTotalUseAble = Infinity;
      } else {
        // 有不限额不判断
        if (values.relatedMattersAddList.value.find((item: any) => item.matterTotalUseAble === -1)) {
          matterTotalUseAble = Infinity;
        } else {
          matterTotalUseAble = values.relatedMattersAddList.value.reduce((pre: number, next: any) => pre + next.matterTotalUseAble, 0);
        }
      }
      // 先不判断可用授信额度 authorizeAmountUsable
      const minNum = userId === principalCode ? Math.min(projectBalance, matterTotalUseAble) : Math.min(projectBalance, matterTotalUseAble, authorizeAmount);
      console.log(projectBalance, authorizeAmountUsable, authorizeAmount, matterTotalUseAble);
      console.log(totalAmount, minNum);
      const obj = {
        [projectBalance]: '项目余额',
        [matterTotalUseAble]: '事项余额',
        [authorizeAmount]: '授权金额'
        // [authorizeAmountUsable]: '可用授权金额'
      };
      if (totalAmount > minNum) {
        return Toast.fail(`申报总额不得超过${obj[minNum]}。`);
      }

      if (userId !== principalCode) {
        if (totalAmount > authorizeAmountUsable && authorizeAmountUsable != -1) {
          // return Toast.fail(`申报总额不得超过可用授权金额。`);
        }
      }
    } catch (e) {
      console.log(e);
    }


    let choosePersons = [];
    let processValidateResult: ProcessValidateResult = {} as ProcessValidateResult;
    if (this.processValidator) {
      processValidateResult = this.processValidator();
      choosePersons = processValidateResult.value;
      if (!processValidateResult.result) {
        Toast.fail(processValidateResult.message);
        return;
      }
    }
    if (this.props.dispatch) {
      this.setState({
        loading: true
      });
      this.props.dispatch(this.getActions({
        extra,
        values,
        flag,
        choosePersons
      })).then((res?: any) => {
        this.setState({
          loading: false
        });
        clearRouteBlocker();
        if (res && res.status == 200) {
          if (flag === 'draft') {
            Toast.success('保存草稿成功');
          } else {
            Toast.success('提交成功');
          }
          this.onCancel();
        } else {
          Toast.fail(res?.message);
        }
      }).catch((e: any) => {
        console.log(e);
        this.setState({
          loading: false
        });
      });

    }
  };

  // 跳转到记录
  onCancel() {
    const applyTypeFromUrl = this.getSearchName('applyType');
    switch (applyTypeFromUrl) {
      case applyType.STUDENT_LABOUR_APPLY:
        this.props.history.replace('/declare/2');
        break;
      case applyType.ONLINE_DOCUMENT_APPLY:
        this.props.history.replace('/official-doc/2');
        break;
      default:
        this.props.history.replace('/declare/2');
        break;
    }
  }

  public setValidateMethod = memoize((mth?: ProcessValidator) => {
    this.processValidator = mth;
  });

  render() {
    const props = this.props;
    const state = this.state;

    return (
      <div className={styles.applyWrap} style={{ height: window.screen.height }}>
        <div className={styles.applyPage}>
          <div className={styles.scrollWrap}>
            <div className={styles.applyForm}>
              <div className={styles.header}>
                <div className={styles.title}>{props.location?.query?.title}</div>
              </div>
              <div className={styles.formContent}>
                {state.formData ? (
                  <Render
                    form={props.form}
                    formValues={this.state.formValues}
                    value={this.state.formShowData}
                    componentClasses={PCComponents}
                  />
                ) : null}
                {state.formData ? (
                  <div className={styles.applyFormProcess}>
                    <ProcessSteps
                      ref={this.processRef}
                      setValidateMethod={this.setValidateMethod}
                      historyTask={state.historyTaskList}
                      form={props.form}
                      formData={state.formData}
                      formValues={this.state.formValues}
                      query={this.getSearchName()}
                      choosePersons={this.state.choosePersons}
                    />
                  </div>
                ) : null}
              </div>
            </div>
          </div>
        </div>
        <div className={styles.footer}>
          {/* <Button
            onClick={() => this.onOk('draft')}
            loading={this.submitType === 'draft' && this.state.loading}
          >
            保存草稿
          </Button> */}
          <Button onClick={() => this.onOk('submit')} loading={this.submitType === 'submit' && this.state.loading} type="primary">
            提交
          </Button>
        </div>
        <Prompt message={(nextRoute) => setRouteBlocker(props.history, nextRoute)} />
      </div>
    );
  }
}

export default connect(({ capproval, loading, common }: ConnectState) => {
  return {
    loading: loading.effects['capproval/startProcess'],
    formData: capproval.formData,
    userInfo: common?.userInfo
  };
})(createDOMForm({
  onFieldsChange: (props: { form: any; applyType: string; history: any }) => {
    const searchArr = props.history?.location?.search?.split('?')[1].split('&');
    const searchParams: any = {};
    searchArr?.forEach((item: any) => {
      searchParams[item.split('=')[0]] = item.split('=')[1];
    });
    if (props.form.isFieldsTouched()) {
      window.routesBlockerList = [searchParams.applyType];
    }
  },
  // 监听提交页面数值变动
  onValuesChange: async (props: any) => {
    // window.routesBlockerList = ['applyChange'];
    await props.form?.validateFields();
    const applyTypeFormUrl = getSearchName('applyType');
    const { matterAddList } = props.form.getFieldsValue();
    if (applyTypeFormUrl === applyType.ONLINE_DOCUMENT_APPLY && !matterAddList?.length) {
      return;
    }
    props.dispatch({
      type: 'capproval/updateProcess'
    });
  }
} as IApprovalModal)(ApprovalModal));
